#ifndef _NTH_LIB_H
#include <nth-lib.h>
#endif

#ifndef _STDLIB_H
#include <stdlib.h>
#endif

#ifndef _STRING_H
#include <string.h>
#endif

int Clean_Nth_Plugin(struct Nth_Plugin * nth_plugin){

	if (!nth_plugin){
		return NTH_ERROR_NULL_POINTER;
	}

	if (nth_plugin->plugin_name){
		free(nth_plugin->plugin_name);
		nth_plugin->plugin_name = 0;
	}

	if (nth_plugin->plugin_description){
		free(nth_plugin->plugin_description);
		nth_plugin->plugin_description = 0;
	}

	return 0;
}

int Initialize_Nth_Plugin(struct Nth_Plugin * nth_plugin){

	char plugin_name[] = "--results-dir";
	char plugin_desc[] = "Path in which to store results";

	if (!nth_plugin){
		return NTH_ERROR_NULL_POINTER;
	}

	nth_plugin->plugin_name = malloc(sizeof(plugin_name));

	if (!nth_plugin->plugin_name){
		return NTH_ERROR_NO_MEMORY;
	}

	memcpy(
		nth_plugin->plugin_name,
		plugin_name,
		sizeof(plugin_name)
	);

	nth_plugin->plugin_description = malloc(sizeof(plugin_desc));

	if (!nth_plugin->plugin_description){
		free(nth_plugin->plugin_name);
		nth_plugin->plugin_name = 0;
		return NTH_ERROR_NO_MEMORY;
	}

	memcpy(
		nth_plugin->plugin_description,
		plugin_desc,
		sizeof(plugin_desc)
	);

	nth_plugin->plugin_callback = Nth_Plugin_Callback;

	return 0;
}

int Nth_Plugin_Callback(
	struct Nth_Program * nth_program,
	struct Nth_Number * plugin_number
){
	int error = 0;

	struct Nth_Variable results_dir;

	results_dir.variable_name = "results-dir";
	results_dir.variable_value = 0;

	error = Get_Next_Nth_Argument(
		nth_program,
		&results_dir.variable_value
	);

	if (error){

		Push_Nth_Failure(
			nth_program,
			"Nth_Plugin_Callback",
			"Failed to get new results path"
		);

		return 1;
	}

	error = Iterate_Nth_Argument(nth_program);

	if (error){

		Push_Nth_Failure(
			nth_program,
			"Nth_Plugin_Callback",
			"Failed to iterate passed results path"
		);

		return 1;
	}

	error = Set_Nth_Variable(
		nth_program,
		&results_dir
	);

	if (error){

		Push_Nth_Failure(
			nth_program,
			"Nth_Plugin_Callback",
			"Failed to set new results path"
		);

		return 1;
	}

	error = Evaluate_Nth_Expression(
		nth_program,
		plugin_number
	);

	if (error){

		Push_Nth_Failure(
			nth_program,
			"Nth_Plugin_Callback",
			"Failed to evaluate next expression"
		);

		return 1;
	}

	return 0;
}

